<template>
  <!-- 创建家庭对话框 -->
  <el-dialog
    v-model="visible"
    width="500px"
    :draggable="true"
    class="family-dialog"
  >
    <el-form
      ref="formRef"
      :model="localFormData"
      label-width="100px"
      :rules="rules"
      class="family-form"
    >
      <el-form-item prop="name" label="家庭名称">
        <el-input
          v-model="localFormData.name"
          placeholder="请输入家庭名称"
          clearable
        />
      </el-form-item>

      <el-form-item label="地区" prop="address">
        <el-cascader
          placeholder="请选择地区"
          :options="addressList"
          :props="cityProps"
          v-model="addressIds"
          popper-class="pc-sel-area-cascader"
          separator="-"
          @change="handleAddressChange"
        />
      </el-form-item>
      <el-form-item label="地址" prop="detailAddress">
        <el-input
          v-model="localFormData.detailAddress"
          placeholder="请输入详细地址"
          class="mt-2"
        />
      </el-form-item>

      <el-form-item label="家庭描述">
        <el-input
          v-model="localFormData.description"
          placeholder="请输入家庭描述（可选）"
          type="textarea"
          :rows="3"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button color="#1F63FF" @click="save">确定</el-button>
    </template>
  </el-dialog>





</template>

<script setup lang="ts">
import {ref, reactive, computed, watch} from 'vue'
import {type FormInstance, type FormRules} from 'element-plus'
import addressData from '@/assets/address.json'
import type {FamilyForm} from "@/api/family/type.ts";

const props = defineProps<{
  visible: boolean,
  formData: FamilyForm
}>()

const emit = defineEmits(['update:visible', 'update:form-data', 'reset', 'save', 'refresh'])

// 控制对话框显示
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const formRef = ref<FormInstance>()

const addressList = ref(addressData);
const cityProps = reactive({
  value: "code",
  label: "name",
  children: "children",
});
// 表单数据
const localFormData = ref({
  ...props.formData
})

watch(() => props.formData, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(localFormData.value)) {
    localFormData.value = {...newVal};
    // 更新地区选择器
    if (newVal.provinceId && newVal.cityId && newVal.districtId) {
      addressIds.value = [newVal.provinceId, newVal.cityId, newVal.districtId];
    }else {
      addressIds.value = [];
    }
  }
}, {deep: true, immediate: true});

const addressIds = ref([localFormData.value.provinceId, localFormData.value.cityId, localFormData.value.districtId])

/**
 * 地区选择改变
 */
function handleAddressChange() {
  if (addressIds.value.length === 3) {
    const [provinceId, cityId, districtId] = addressIds.value;
    localFormData.value.provinceId = provinceId;
    localFormData.value.cityId = cityId;
    localFormData.value.districtId = districtId;
    const names: string[] = [];

    // 递归查找地区名称
    const findNames = (data: any[], codes: string[], level = 0) => {
      if (level >= codes.length) return;

      const currentCode = codes[level];
      const foundItem = data.find(item => item.code === currentCode);

      if (foundItem) {
        names.push(foundItem.name);
        if (foundItem.children && level < codes.length - 1) {
          findNames(foundItem.children, codes, level + 1);
        }
      }
    };

    findNames(addressList.value, addressIds.value);
    localFormData.value.address = names.join('-');
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    {required: true, message: "请输入家庭名称", trigger: "blur"},
    {min: 3, max: 20, message: "家庭名称长度为3-20位", trigger: "blur"},
  ],
  address: [
    {required: true, message: "请选择地区", trigger: "change"}
  ],
  detailAddress: [
    {required: true, message: "请输入详细地址", trigger: "blur"}
  ]
})

/**
 * 添加新家庭
 */
function save() {
  formRef.value?.validate(valid => {
    if (valid) {
      emit('save', localFormData.value)
      reset()
    }
  })
}

function reset() {
  formRef.value?.resetFields()
  addressIds.value = [];
  emit('reset')
}



</script>

<style scoped lang="scss">
.mt-2 {
  margin-top: 8px;
}

:deep(.el-input-group__append) {
  padding: 0 10px;
}
</style>
